<?php
/**
 * 合作伙伴类
 */
class partnerModel
{

    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /**
     * 设置错误信息
     * @param int $errorId  接口错误ID
     */
    public function getMsg($errorId)
    {
        $actionErrorTexts = array(
            10000   => '成功',
            10001   => '跑步用户不存在',
            10002   => '该跑步账号已与其他合作方账号绑定',
            10003   => '绑定失败',
            10004   => '跑步用户ID不能为空',
            10005   => '合作方用户ID不能为空',
            10006   => '解绑操作失败',
            10007   => '该合作方账号已与其他跑步用户绑定',
            20001   => 'PPTV用户不存在',
            20002   => '账户间无关联关系',
            30000   => '签名不正确',
            30001   => '错误的请求',
        );
        $this->base->result = array(
            'status' => $errorId,
            'msg' => $actionErrorTexts[$errorId],
        );
    }
    /**
     * 检查合作伙伴身份
     * @param str $appid
     * @param str $appkey
     * @return int $pptvUserId
    */
    public function checkPartner($appid, $appkey)
    {
        $result = array();
        $partner = array(
                'PPTV' => '421873b88778fdcaded6d00d3effbde5'
        );
        $value = md5('JOGGERS'.$appid.'SOBIGTHISWORLD'.$appkey.'ANDIWANNASEE');
        if(isset($partner[$appid]) && $partner[$appid] = $value)
        {
            $result = true;
        }
        return $result;
    }
    /**
     * 检查用户与合作方绑定关系
     * @param str $appid
     * @param int $uid
     * @return int $puid  合作方用户ID
    */
    public function checkPartnerBind($appid, $uid, $puid)
    {
        $redisPartnerKey = REDIS_PREFIX.$appid.'Bind';
        $redisRunKey = REDIS_PREFIX.'RunBind'.$appid;

        $checkUid = $this->redis->hget($redisPartnerKey, urldecode($puid));
        $this->loginfo("88888=".$checkUid . ";" . $redisPartnerKey . ";=" . urldecode($puid));
        //$checkUid = intval($checkUid);
        $checkpuid = $this->redis->hget($redisRunKey, $uid);

        return array('checkUid' => $checkUid,'checkpuid' => $checkpuid);
    }

   

    /**
     * pptv 绑定
     * @param str $appid
     * @param int $uid
     * @param int $puid  合作方用户标识
     * @return boolen
    */
    public function bind($appid, $uid, $puid)
    {
        $result = false;
        if($appid && $uid > 0 && $puid)
        {
            $time = $this->base->time;
            $insert = array('appid' => $appid,
                            'uid' => $uid,
                            'puid' => urldecode($puid),
                            'status' => 1,
                            'addtime'    => $time,
                            'updatetime' => $time
                        );
            if($this->db->insertRowTable('r_partner', $insert))
            {
                $this->redis->hset(REDIS_PREFIX.$appid.'Bind', urldecode($puid), $uid);
                $this->redis->hset(REDIS_PREFIX.'RunBind'.$appid, $uid, urldecode($puid));
                $result = true;
            }
        }
        return $result;
    }
    /**
     * pptv 解除绑定
     * @param str $appid
     * @param int $uid
     * @param int $puid
     * @return boolen
    */
    public function unbind($appid, $uid, $puid)
    {
        $result = false;
        if($uid > 0 && $puid)
        {
            $time = $this->base->time;

            $puid = urldecode($puid);
            // $rst = $this->db->getRowTable('r_partner', array(), "appid='{$appid}' and uid = '{$uid}' and puid = '{$puid}'");
            // $pid = empty($rst) ? null : !isset($rst['id']) ? null : $rst['id'];
            //$this->loginfo("7777777pid====".$pid);

            $update = array(
                            'appid' => $appid,
                            'uid' => $uid,
                            'puid' => $puid,
                            'status' => 2,
                            'updatetime' => $time,
                        );
            $this->loginfo("7777====".$appid . ";" . $uid . "" . $puid);
            $rst = $this->db->delDataTable('r_partner',"appid='{$appid}' and uid = '{$uid}' and puid = '{$puid}'");
            //if($this->db->updateRowTable('r_partner', $update))
            $this->loginfo("4444====".$rst);
            if($rst)
            {
                $this->redis->hdel(REDIS_PREFIX.$appid.'Bind', urldecode($puid));
                $this->redis->hdel(REDIS_PREFIX.'RunBind'.$appid, urldecode($uid));
                $result = true;
            }
        }
        return $result;
    }
    /**
     * pptv 发送跑步数据
     * @param int $uid
     * @param array $runData
     * @return int    -1:参数错误  0:失败需要重发  1:成功  2:失败，无效的绑定关系
    */
    public function sendRunData($appid, $uid, $puid, $runData)
    {
        $result = -1;
        $this->loginfo("发送数据44444444444====".$puid . ";" .$uid. ";" .$appid. ";".var_export($runData,true));

        if(!$puid || !$uid || !$appid || empty($runData) || !isset($runData['runId']))
        {
            return $result;
        }
        $this->loginfo("发送数据555555555555555====".$appid);
        $url = $this->getSendUrl($appid);
        if(!$url)
        {
            return $result;
        }
        $this->loginfo("发送数据666666666666====".var_dump($uid) . "=" . var_dump($puid).  "=" . var_dump($runData));
        $postData = array('runUserId' => $uid,
                      'pptvUserId' => $puid,
                      'runUserType' => 'hupu',
                      'format' => 'json',
                      'runData' => $runData
            );
        //$postData['sign'] = Md5(urlencode($puid.$uid.'hupu','utf-8'));
        $postData['sign'] = Md5(urlencode($puid."$".$uid."$"."hupu"));
        //$rel = common::getContents($url, $postData, 10, 'POST');
        $rel = $this->curl($url, $postData);
        $this->loginfo("发送数据777777799999999999====".$url);
        $this->loginfo("发送数据7777777777777777====".var_export($postData,true));
        $this->loginfo("发送数据888888888888888====".var_export($rel,true));
        $rel = @json_decode($rel);
        if(!is_array($rel))
        {
            $result = 0;
        }
        else if($rel['flag'] != 0)
        {
            $result = 2;
        }
        else
        {
            $result = 1;
        }
        return $result;
    }
    /**
     * 获取第三方发送跑步数据的地址
     * @param str $appid
     * @return str    url
    */
    private function getSendUrl($appid = 'PPTV')
    {
        //$sendUrlArr = array('PPTV' => 'https://api.usergrowth.pptv.com/hupu/receiveData');
        //return isset($sendUrlArr[$appid]) ? isset($sendUrlArr[$appid]) : '';
        return "https://api.usergrowth.pptv.com/hupu/receiveData";
    }
    /**
     * 获取第三方绑定回调的地址
     * @param str $appid
     * @return str    url
    */
    private function getBindCallbackUrl($appid = 'PPTV')
    {
        //$bindCallbackUrlArr = array('PPTV' => 'https://api.passport.pptv.com/v3/cooperateBound.do');
        //return isset($bindCallbackUrlArr[$appid]) ? isset($bindCallbackUrlArr[$appid]) : '';
        return "https://api.passport.pptv.com/v3/cooperateBound.do";
    }
    /**
     * 第三方绑定回调
     * @param str $appid
     * @param str $puid   第三方用户名
     * @param int $uid   虎扑跑步id
     * @param str $format 返回类型，可以为xml,json,jsonp
     * @param str $uid
     * @return
    */
    public function bindCallback($appid, $puid, $uid, $format='json')
    {
        $url = $this->getBindCallbackUrl($appid);
        if(!$url)
        {
            return;
        }
        $this->loginfo("2222====".$puid);
         $this->loginfo("2222====".urldecode($puid));
        $data = array('username' => urldecode($puid),
                      'cooperateId' => $uid,
                      'cooperateType' => 'hupu',
                      'format' => $format,
                      'sign' => Md5(urlencode(urldecode($puid)."$".$uid."$"."hupu")),
            );
        $this->loginfo("2====".$url);
        $this->loginfo("3====".var_export($data,true));
        $rst = common::getContents($url, $data, 10, 'POST');
        //$rst = $this->curl($url, $data);
        $this->loginfo("4====".$rst);
        return;
    }

    public function curl($action,$params){

$this->loginfo("curl信息链接====".$action);//
    $this->loginfo("curl信息参数====".var_export($params,true));//
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $action);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
$this->loginfo("curl信息====".$ret);//
        $error = curl_error ($ch);//需放在curl_close($curl)执行之前
$this->loginfo("错误信息====".$error);//

        if (false === $ret) {
          $ret =  curl_errno($ch);
        }

        curl_close($ch);
        return $ret;
    }

    private function loginfo($content){
        //文件所处目录
        $path = $this->base->config['log-dir'].'partner/';
        //查看文件目录是否存在,不存在创建
        !file_exists($path) && mkdir($path);
        //文件名称及类型
        $logName = date('Ymd').'.txt';
        //写入方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。
        $fp = fopen($path.$logName, "a");
        //文件内容前缀
        $log_prefix = '---start---'.date('Y-m-d H:i:s')."---\n";
        //文件内容后缀
        $log_suffix = '---end---'.date('Y-m-d H:i:s')."---\n";
        //写入内容
        fwrite($fp, $log_prefix . var_export($content,true) . "\n" . $log_suffix);
        //写入换行
        fwrite($fp, "\n");
        //关闭
        fclose($fp);
    }
    
    /*
     * 无appid 绑定用户
     */
    public function bindByPartnerName($data)
    {
        if(!isset($data['uid']) || !isset($data['partner_name'])){
            return false;
        }
        $row['uid'] = $data['uid'];
        $row['partner_name'] = $data['partner_name'];
        $row['partner_uid'] = isset($data['partner_uid']) ? $data['partner_uid'] : '';
        $row['partner_eid'] = isset($data['partner_eid']) ? $data['partner_eid'] : '';
        $row['addtime'] = isset($data['addtime']) ? $data['addtime'] : time();
        $this->db->insertRowTable('r_partner_user',$row);
        
    }
    
    /*
     * 检测无appid绑定的用户
     */
    public function getUserInfo($uid,$partner_name)
    {
        return $this->db->getRowTable('r_partner_user',array(),"partner_name='{$partner_name}' and uid = '{$uid}'");
    }
}

?>